package com.chainyoung.component_tmperson.ui.activity.cloudwallet;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.common_widget.loadsir.callback.Callback;
import com.chainyoung.common.common_widget.loadsir.core.LoadService;
import com.chainyoung.common.common_widget.loadsir.core.LoadSir;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.custom_widget.EmptyCallback;
import com.chainyoung.common.custom_widget.LoadingCallback;
import com.chainyoung.common.custom_widget.RetryCallback;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.view.ActionSheetDialog;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.entity.Purse;
import com.chainyoung.component_tmperson.entity.RechargeRecord;

import com.chainyoung.component_tmperson.ui.activity.MakeCashActivity;
import com.chainyoung.component_tmperson.ui.adapter.MakeCashRecordAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.RechargeRecordContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.RechargeRecordPresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.component_tmperson.constant.PersonStringConstant.COIN_CN_NAME;
import static com.chainyoung.component_tmperson.constant.PersonStringConstant.COIN_LOGO;
import static com.chainyoung.component_tmperson.constant.PersonStringConstant.COIN_NAME;
import static com.chainyoung.component_tmperson.constant.PersonStringConstant.COIN_TOTAL_NAME;
import static com.chainyoung.component_tmperson.constant.PersonStringConstant.ZC_FEE;

public class PurseActivity extends BaseActivity<RechargeRecordPresenter> implements RechargeRecordContract.View {


    @BindView(R2.id.iv_logo)
    ImageView ivLogo;
    @BindView(R2.id.tv_num)
    TextView tvNum;
    @BindView(R2.id.tv_price_cny)
    TextView tvPriceCny;
    @BindView(R2.id.tv_available)
    TextView tvAvailable;
    @BindView(R2.id.tv_locked)
    TextView tvLocked;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;


    private Purse purse;

    private final int TYPE_ALL = 0;
    private final int TYPE_WITHDRAW = 2;
    private final int TYPE_CHARGE = 1;

    private int recordType = TYPE_ALL;//记录类型

    private int pageNo = 1;
    private List<RechargeRecord> mData = new ArrayList<>();
    private boolean isCanloadMore;
    private MakeCashRecordAdapter makeCashRecordAdapter;
    private String coinName;
    private LoadService loadService;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected boolean useDefaultStatusBar() {
        return false;
    }

    @Override
    protected void initUI() {
        purse = (Purse) getIntent().getSerializableExtra("purseItem");
        coinName = purse.getName();
        setCurrentTitle(coinName.toUpperCase() + "/" + purse.getTitle());
        mCurrentTtile.setTextColor(ContextCompat.getColor(mContext, R.color.white));
        mBarLeftImageView.setImageResource(R.mipmap.ic_back_white);
        toolbar.setBackgroundColor(ContextCompat.getColor(mContext, R.color._303e63));
        initView();
        initRecyclerList();
    }

    private void initView() {
        Glide.with(mContext).load(purse.getImg()).apply(RequestOptions.errorOf(R.mipmap.ic_default)).into(ivLogo);
        tvNum.setText(StringUtil.subZeroAndDot(new BigDecimal(purse.getXnbz()).setScale(6, BigDecimal.ROUND_DOWN) + ""));
        tvPriceCny.setText(String.format("≈CNY %s", StringUtil.subZeroAndDot(new BigDecimal(purse.getZhehe_cny()).setScale(2, BigDecimal.ROUND_DOWN).toString())));
        tvAvailable.setText("可用：" + StringUtil.subZeroAndDot(new BigDecimal(purse.getXnb()).setScale(6, BigDecimal.ROUND_DOWN).toString()));
        tvLocked.setText("冻结：" + StringUtil.subZeroAndDot(new BigDecimal(purse.getXnbd()).setScale(6, BigDecimal.ROUND_DOWN).toString()));

    }

    private void initRecyclerList() {
        makeCashRecordAdapter = new MakeCashRecordAdapter(mData, mContext);
//        DividerItemDecoration itemDecoration = new DividerItemDecoration(getBaseContext(), DividerItemDecoration.VERTICAL);
//        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_line));
//        rvList.addItemDecoration(itemDecoration);
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        rvList.setAdapter(makeCashRecordAdapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    loadData();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                loadData();
            }
        });

        LoadSir loadSir = new LoadSir.Builder()
                .addCallback(new LoadingCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new RetryCallback())
                .setDefaultCallback(LoadingCallback.class)
                .build();
        loadService = loadSir.register(refreshLayout, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                pageNo = 1;
                loadData();
//                if (recordType == TYPE_WITHDRAW) {
//                    loadChargeRecord();
//                } else {
//                    loadWithDrawRecord();
//                }

            }
        });


    }

    @Override
    protected void initData() {
        pageNo = 1;
        loadData();
        //loadChargeRecord();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_purse;
    }

    //    ----------------------------------------点击事件---------------------------------------------------------


    /**
     * 充值
     */
    @OnClick(R2.id.tv_charge)
    void charge() {
        Intent intent = new Intent(mContext, ChargeActivity.class);
        intent.putExtra(COIN_NAME, purse.getName());
        intent.putExtra(COIN_CN_NAME, purse.getTitle());
        intent.putExtra(COIN_TOTAL_NAME, purse.getJs_yw());
        intent.putExtra(COIN_LOGO, purse.getImg());
        mContext.startActivity(intent);
    }

    /**
     * 提现
     */
    @OnClick(R2.id.tv_withdraw)
    void withDraw() {
        Intent intent = new Intent(mContext, MakeCashActivity.class);
        intent.putExtra(COIN_NAME, purse.getName());
        intent.putExtra(COIN_CN_NAME, purse.getTitle());
        intent.putExtra(ZC_FEE, purse.getZcfee());
        mContext.startActivity(intent);
    }

    /**
     * 交易
     */
    @OnClick(R2.id.tv_trade)
    void trade() {
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_SELECT_TRADE_MARKET)
                .withString("coinName", coinName.toUpperCase())
                .withBoolean("isFromPurse", true)
                .navigation(mContext);
    }


    //-------------------------------------------网络请求------------------------------------------------------------

    private void loadData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", coinName);
        map.put("page", pageNo);
        map.put("limit", LibConstant.PAGE_SIZ);
        map.put("transfer_type", recordType);
        mPresenter.getTransferRecord(map);
    }


    @Override
    public void onGetRechargeRecordSuccess(CommonList<RechargeRecord> data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (pageNo == 1) {
            mData.clear();
        }
        if (data == null) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
            if (pageNo == 1) {
                loadService.showCallback(EmptyCallback.class);
            }
            return;
        }
        mData.addAll(data.getList());
        if (data.getList().size() < LibConstant.PAGE_SIZ) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
        } else {
            isCanloadMore = true;
            refreshLayout.setEnableLoadMore(true);
        }
        if (mData.isEmpty()) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();
        }
        // makeCashRecordAdapter.setType(recordType);
        makeCashRecordAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetRechargeRecordFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        loadService.showCallback(RetryCallback.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        pageNo = 1;
        loadData();
    }
}
